<?php

namespace Project\Admin\Middleware;

use Closure;
use Dingo\Api\Routing\Helpers;
use Illuminate\Http\Request;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Facades\JWTAuth;
use Traits\Response;

class Authenticate
{
    use Helpers, Response;

    protected $auth;

    public function __construct()
    {
        $this->auth = auth(config('admin.admin_guard'));
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        $this->authenticate();

        return $next($request);
    }

    /**
     * 检查是否存在 Token 的头数据
     *
     * @return void
     */
    protected function checkForToken()
    {
        if (!$this->auth->parser()->hasToken()) {
            return $this->fail('请登录后操作');
        }
    }

    /**
     * 检查是否用户合法
     *
     * @return void
     */
    protected function authenticate()
    {
        $this->checkForToken();
        try {
            $id = $this->auth->getPayload()->get('sub');
            if (!$this->auth->byId($id)) {
                return $this->fail('非法用户');
            }
        } catch (JWTException $e) {
            return $this->fail('登录失效.' . config('admin.debug') ? $e->getMessage() : '');
        }
    }

    /**
     * 刷新 Token 并设置头信息
     *
     * @return void
     */
    protected function setAuthentHeader($token = null)
    {
        $token = $token ?: $this->auth->refresh();
        response()->headers->set('Authorization', 'Bearer ' . $token);

        return response();
    }
}